<template>
  <div id="interMethodExternalDiv">
    <Splitpanes horizontal :dbl-click-splitter="false">
      <Pane size="10">
        <el-form inline>
          <el-form-item label="接口地址：">
            <vxe-textarea style="width:500px;" v-model="currentRow.methodDataBase" placeholder="请输入接口地址" :autosize="{ minRows: 1, maxRows: 3 }"></vxe-textarea>
          </el-form-item>
        </el-form>
      </Pane>
      <Pane>
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-input v-model="keyvalue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @keydown="findSysInterfaceMethodExtParams" @search-click="findSysInterfaceMethodExtParams" @clear="findSysInterfaceMethodExtParams"></vxe-input>
            <vxe-button type="text" class="button-blue" content="新增" @click="insertRow"></vxe-button>
            <vxe-button type="text" class="button-blue" content="保存" @click="saveInfo"></vxe-button>
            <vxe-button type="text" class="button-red" content="删除" @click="deleteExtParam"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-upload" :content="currentRow.dataTypeName" @click="upload"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="复制" @click="copy"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="粘贴" @click="paste"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="tableBox">
          <vxe-table ref="extParamsTableRef" :border="'inner'" show-header-overflow :data="tableList" @current-change="extCurrentRowChange" :row-config="{ isCurrent: true }" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showIcon: false }" :expand-config="{ expandAll: true, reserve: true }" :tree-config="{
            expandAll: true,
            transform: currentRow.dataType == 'HL7'?false:true,
            rowField: 'paramId',
            parentField: 'paramParentId'
          }" height="auto" class="mytable-scrollbar" resizable show-overflow keep-source>
            <vxe-column type="checkbox" width="30"></vxe-column>
            <vxe-column type="seq" title="序号" width="50"></vxe-column>
            <vxe-column field="extCode" title="外源参数" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" width="140">
              <template #edit="{ row }">
                <vxe-input v-model="row.extCode" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="symbol" title="比较" :edit-render="{}" width="100">
              <template #default="{ row }">
                <div>{{ emSymbolArr.filter(data => data.value === row.symbol)[0].label }}</div>
              </template>
              <template #edit="{ row }">
                <vxe-select v-model="row.symbol" transfer>
                  <vxe-option v-for="item in emSymbolArr" :key="item.value" :value="item.value" :label="item.label"></vxe-option>
                </vxe-select>
              </template>
            </vxe-column>
            <vxe-column field="inCodeNo" title="入参" :edit-render="{}" width="80">
              <template #edit="{ row, rowIndex }">
                <VxePulldownSelection v-if="!row.isFixed" :isChild="true" :childIndex="row.id" :ref="'fieldRef' + rowIndex" :url="'/api/sys/getInterfaceDictParamList'" @confirmClick="pulldownSelectConfirm" :tableColumn="[
                  { field: 'code', title: '字段' },
                  { field: 'common', title: '出参名称' }
                ]" :aimKeys="[
                  { aimKey: 'inCodeNo', rowKey: 'code' },
                  { aimKey: 'inCodeId', rowKey: 'id' },
                  { aimKey: 'inCodeNa', rowKey: 'common' },
                  { aimKey: 'inCodeDtype', rowKey: 'coloumType' },
                  { aimKey: 'inCodeDes', rowKey: 'common' },
                  { aimKey: 'inCode', rowKey: 'entity' }
                ]" :displayTexts="['common']" :displayTextObj="row.inCodeNa ? row.inCodeNa : ''" :dataObj="{ dictId: currentRow.interfaceDictId, type: 1 }" />
                <vxe-input v-if="row.isFixed" v-model="row.inCodeNo" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="inCodeNa" title="参数名称" width="85">
              <template #edit="{ row }">
                <vxe-input v-model="row.inCodeNa" type="text"></vxe-input>
              </template>
            </vxe-column>
            <!-- <vxe-column field="extCodeNa" title="入参名称" width="180">
              <template #edit="{ row }">
                <vxe-input v-model="row.extCodeNa" type="text"></vxe-input>
              </template>
            </vxe-column>-->
            <vxe-column field="isFixed" title="是否固定值" width="100" align="center">
              <template #default="{ row }">
                <el-switch v-model="row.isFixed" inline-prompt active-text="是" inactive-text="否"></el-switch>
              </template>
            </vxe-column>
            <vxe-column field="inCodeDtype" title="入参数据类型" :edit-render="{}" width="70">
              <template #default="{ row }">
                <span>{{ formatCommon(coloumTypeList, row.inCodeDtype) }}</span>
              </template>
              <template #edit="{ row }">
                <!-- <vxe-input v-model="row.inCodeDtype" type="text" placeholder="入参数据类型"></vxe-input> -->
                <vxe-select v-model="row.inCodeDtype" transfer>
                  <vxe-option v-for="item in coloumTypeList" :key="item.id" :value="item.code" :label="item.name"></vxe-option>
                </vxe-select>
              </template>
            </vxe-column>
            <vxe-column field="extCodeDes" title="外源参数说明" :edit-render="{}" width="100">
              <template #edit="{ row }">
                <vxe-input v-model="row.extCodeDes" type="text" placeholder="外源参数说明"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="extIsNull" title="外源参数允许为空" :edit-render="{}" width="80">
              <template #edit="{ row }">
                <vxe-checkbox v-model="row.extIsNull" content :checked-value="1" :unchecked-value="0"></vxe-checkbox>
              </template>
              <template #default="{ row }">
                <vxe-checkbox v-model="row.extIsNull" content :checked-value="1" :unchecked-value="0"></vxe-checkbox>
              </template>
            </vxe-column>
            <!-- <vxe-column field="inCodeDes" title="入参说明" :edit-render="{}" width="100">
              <template #edit="{ row }">
                <vxe-input v-model="row.inCodeDes" type="text" placeholder="入参说明"></vxe-input>
              </template>
            </vxe-column> -->
            <vxe-column field="paramCompare" title="参数对照" width="100">
            </vxe-column>
            <vxe-column title="操作" align="center">
              <template #default="{ row, rowIndex }">
                <vxe-button type="text" status="primary" icon="vxe-icon-edit" circle @click="handleUpdate(row, rowIndex)"> </vxe-button>
                <!-- <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click="handleDelete(row)"> </vxe-button> -->
              </template>
            </vxe-column>
          </vxe-table>
          <vxe-modal class-name="animation-slide-right" destroy-on-close v-if="moduleDialog1" v-model="moduleDialog1" title="添加参数映射" width="30vw" height="40vh" show-zoom resize>
            <vxe-button content="新增" type="text" class="button-blue" icon="vxe-icon-add" @click="paramCompareAdd"> </vxe-button>
            <vxe-button content="保存" type="text" class="button-blue" icon="vxe-icon-save" @click="paramCompareSave"> </vxe-button>
            <vxe-table ref="refParamCompare" border resizable show-overflow :data="paramComoareList" :edit-config="{ trigger: 'click', mode: 'cell' }">
              <vxe-column type="seq" width="60"></vxe-column>
              <vxe-column field="sourceValue" title="源值" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row }">
                  <vxe-input v-model="row.sourceValue" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="targetValue" title="目标值" :edit-render="{}">
                <template #edit="{ row }">
                  <vxe-input v-model="row.targetValue" type="text" placeholder="请输入昵称"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column title="操作" align="center">
                <template #default="{ row, rowIndex }">
                  <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click="handleParamCompareDelte(rowIndex)"> </vxe-button>
                </template>
              </vxe-column>
            </vxe-table>
          </vxe-modal>
        </div>
      </Pane>
    </Splitpanes>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted, computed } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { isEmpty } from 'lodash';
import { AppStore } from '@/stores/store';
import SelectDataGrid from '@/components/SelectDataGrid.vue'; //
import VxePulldownSelection from '@/components/VxePulldownSelection.vue';
import { enums } from '@/enums/enumerator.js';
import { IsEmpty } from '@/utils/common';
import { VXETable, VxeFormPropTypes, VxeFormInstance } from 'vxe-table';

let store = AppStore();
defineExpose({ initPage });
let methodId = null;
let moduleDialog1 = ref(false);
let currentRow: any = reactive({});
let currentParamRow: any = reactive({});
let currentParamRowByUpdate: any = reactive({});
let tableList: any[] = reactive([]);
let updateTableList: any[] = reactive([]);
let sqlStr = ref('exec P_Sync_Department');
let sqlStrFull = ref('exec P_Sync_Department @1,@2,@3');
let coloumTypeList = reactive([]);
let paramComoareList = reactive([]);
let emSymbolArr = reactive(enums.emSymbol);
let refParamCompare = ref('');
let fileContent = ref('');
let keyvalue = ref('');

// 请求接口url
let baseRow = {
  id: null,
  extCode: '',
  extCodeNa: '',
  extCodeDtype: '',
  extCodeDes: '',
  extIsNull: 0,
  symbol: 'equal',
  inCodeId: '',
  inCodeNo: '',
  inCodeNa: '',
  isFixed: '',
  inCodeDtype: '',
  inCodeDes: '',
  paramCompare: '',
  isEnable: '',
  seq: '',
  interfaceMethodId: '',
  interfaceId: '',
  interfaceMethodDictId: '',
  leftBracket: 0,
  rightBracket: 0,
  relation: 'and',
  type: 1,
  paramParentId: '',
  paramId: ''
};
let baseRowByUpdte = {
  id: null,
  extCode: '',
  extCodeNa: '',
  extCodeDtype: '',
  extCodeDes: '',
  extIsNull: 0,
  symbol: 'equal',
  inCodeId: '',
  inCodeNo: '',
  inCodeNa: '',
  isFixed: '',
  inCodeDtype: '',
  inCodeDes: '',
  paramCompare: '',
  isEnable: '',
  seq: '',
  interfaceMethodId: '',
  interfaceId: '',
  interfaceMethodDictId: '',
  leftBracket: 0,
  rightBracket: 0,
  relation: 'and',
  type: 2,
  paramParentId: '',
  paramId: ''
};
let sqlType = ref('2');
const extParamsTableRef = ref(null); /**外源参数表格对象 */
const sqlStrFullTxt = computed(() => {
  if (currentRow.sqlType == 2) {
    let r = '';
    let str = '';
    let valeStr = '';
    const ars = tableList;
    let arrayStr = [];
    let valueStr = [];
    if (ars && ars.length > 0) {
      for (const iterator of tableList) {
        for (const key in iterator) {
          if (Object.prototype.hasOwnProperty.call(iterator, key)) {
            if (key === 'extCode') {
              arrayStr.push(iterator[key]);
            }
          }
        }
        for (const key in iterator) {
          if (Object.prototype.hasOwnProperty.call(iterator, key)) {
            const element = iterator[key];
            if (key === 'inCodeNo') {
              let repStr = '';
              switch (iterator.extCodeDtype) {
                case '1':
                case '3':
                  repStr = `'#${iterator[key]}#'`;
                  break;
                case '2':
                  repStr = `#${iterator[key]}#`;
                  break;
                default:
                  repStr = `#${iterator[key]}#`;
                  break;
              }
              valueStr.push(repStr);
            }
          }
        }
      }
      str = '(' + arrayStr.join(',') + ')';
      valeStr = '(' + valueStr.join(',') + ')';
      r = (currentRow.methodDataBase ? currentRow.methodDataBase : '') + '  ' + str + ' VALUES ' + valeStr;
    } else {
      r = currentRow.methodDataBase ? currentRow.methodDataBase : '';
    }
    return r;
  } else if (currentRow.sqlType == 3) {
    let r = '';
    let i = 0;
    let str = '';
    let valeStr = ' SET ';
    const updateArs = updateTableList;
    const ars = tableList;
    if (updateArs && updateArs.length > 0 && ars && ars.length > 0) {
      r = currentRow.methodDataBase ? currentRow.methodDataBase : '';
      updateTableList.map(function (item) {
        valeStr += item.extCode + ' =';
        let repStr = '';
        switch (item.extCodeDtype) {
          case '1':
          case '3':
            valeStr += `'#${item.inCodeNo}#'` + ',';
            break;
          case '2':
            valeStr += `'#${item.inCodeNo}#'` + ',';
            break;
          default:
            valeStr += `'#` + item.inCodeNo + `#'` + ',';
            break;
        }
      });
      for (const iterator of tableList) {
        if (iterator.extIsNull === 0) {
          let arrayStr = [];
          for (const key in iterator) {
            if (Object.prototype.hasOwnProperty.call(iterator, key)) {
              const element = iterator[key];
              if (key === 'leftBracket') {
                arrayStr[0] = '('.repeat(Number(iterator[key]));
              }
              if (key === 'extCode') {
                arrayStr[1] = ' ' + iterator[key];
              }
              if (key === 'symbol') {
                switch (iterator[key]) {
                  case 'greatthan':
                    arrayStr[2] = ' > ';
                    break;
                  case 'greatequalthan':
                    arrayStr[2] = ' >= ';
                    break;
                  case 'lessthan':
                    arrayStr[2] = ' < ';
                    break;
                  case 'lessequalthan':
                    arrayStr[2] = ' <= ';
                    break;
                  case 'equal':
                    arrayStr[2] = ' = ';
                    break;
                  case 'in':
                    arrayStr[2] = ' in ';
                    break;
                  case 'notin':
                    arrayStr[2] = ' not in ';
                    break;
                  case 'like':
                    arrayStr[2] = ' like ';
                    break;
                  case 'notlike':
                    arrayStr[2] = ' not like ';
                    break;
                  default:
                    break;
                }
              }
              if (key === 'inCodeNo') {
                let repStr = '';
                switch (iterator.extCodeDtype) {
                  case '1':
                  case '3':
                    repStr = `'#${iterator[key]}#'`;
                    break;
                  case '2':
                    repStr = `#${iterator[key]}#`;
                    break;
                  default:
                    repStr = `#${iterator[key]}#`;
                    break;
                }
                arrayStr[3] = ' ' + repStr;
              }
              if (key === 'rightBracket') {
                arrayStr[4] = ')'.repeat(Number(iterator[key]));
              }
              if (key === 'relation') {
                if (i < ars.length - 1) {
                  arrayStr[5] = ' ' + iterator[key] + ' ';
                }
              }
            }
          }
          str += arrayStr.join(' ');
          i++;
        }
      }
      r += valeStr.substring(0, valeStr.length - 1) + ' where ' + str;
    } else {
      r = currentRow.methodDataBase ? currentRow.methodDataBase : '';
    }
    return r;
  }
  //存储过程类型下 oracle数据库
  else if (currentRow.sqlType == 5 && currentRow.dbMs == '0') {
    let r = '';
    let i = 0;
    let valeStr = '  ';
    const ars = tableList;
    if (ars && ars.length > 0) {
      r = currentRow.methodDataBase ? currentRow.methodDataBase : '';
      tableList.map(function (item) {
        switch (item.extCodeDtype) {
          case '1':
          case '3':
            valeStr += `'#${item.inCodeNo}#'` + ',';
            break;
          case '2':
            valeStr += `'#${item.inCodeNo}#'` + ',';
            break;
          default:
            valeStr += `'#` + item.inCodeNo + `#'` + ',';
            break;
        }
      });
      r += '(' + valeStr.substring(0, valeStr.length - 1) + ')';
    } else {
      r = currentRow.methodDataBase ? currentRow.methodDataBase : '';
    }
    return r;
  }

  //存储过程类型下 sqlServer数据库
  else if (currentRow.sqlType == 5 && currentRow.dbMs == '1') {
    let r = '';
    let i = 0;
    let valeStr = '  ';
    const ars = tableList;
    if (ars && ars.length > 0) {
      r = currentRow.methodDataBase ? currentRow.methodDataBase : '';
      tableList.map(function (item) {
        valeStr += item.extCode + ' =';
        let repStr = '';
        switch (item.extCodeDtype) {
          case '1':
          case '3':
            valeStr += `'#${item.inCodeNo}#'` + ',';
            break;
          case '2':
            valeStr += `'#${item.inCodeNo}#'` + ',';
            break;
          default:
            valeStr += `'#` + item.inCodeNo + `#'` + ',';
            break;
        }
      });
      r += valeStr.substring(0, valeStr.length - 1);
    } else {
      r = currentRow.methodDataBase ? currentRow.methodDataBase : '';
    }
    return r;
  } else {
    let r = '';
    let str = '';
    let i = 0;
    const ars = tableList.filter((p) => p.extIsNull === 0);
    if (ars && ars.length > 0) {
      for (const iterator of tableList) {
        if (iterator.extIsNull === 0) {
          let arrayStr = [];
          for (const key in iterator) {
            if (Object.prototype.hasOwnProperty.call(iterator, key)) {
              const element = iterator[key];
              if (key === 'leftBracket') {
                arrayStr[0] = '('.repeat(Number(iterator[key]));
              }
              if (key === 'extCode') {
                arrayStr[1] = ' ' + iterator[key];
              }
              if (key === 'symbol') {
                switch (iterator[key]) {
                  case 'greatthan':
                    arrayStr[2] = ' > ';
                    break;
                  case 'greatequalthan':
                    arrayStr[2] = ' >= ';
                    break;
                  case 'lessthan':
                    arrayStr[2] = ' < ';
                    break;
                  case 'lessequalthan':
                    arrayStr[2] = ' <= ';
                    break;
                  case 'equal':
                    arrayStr[2] = ' = ';
                    break;
                  case 'in':
                    arrayStr[2] = ' in ';
                    break;
                  case 'notin':
                    arrayStr[2] = ' not in ';
                    break;
                  case 'like':
                    arrayStr[2] = ' like ';
                    break;
                  case 'notlike':
                    arrayStr[2] = ' not like ';
                    break;
                  default:
                    break;
                }
              }
              if (key === 'inCodeNo') {
                let repStr = '';
                switch (iterator.extCodeDtype) {
                  case '1':
                  case '3':
                    repStr = `'#${iterator[key]}#'`;
                    break;
                  case '2':
                    repStr = `#${iterator[key]}#`;
                    break;
                  default:
                    repStr = `#${iterator[key]}#`;
                    break;
                }
                arrayStr[3] = ' ' + repStr;
              }
              if (key === 'rightBracket') {
                arrayStr[4] = ')'.repeat(Number(iterator[key]));
              }
              if (key === 'relation') {
                if (i < ars.length - 1) {
                  arrayStr[5] = ' ' + iterator[key] + ' ';
                }
              }
            }
          }
          str += arrayStr.join(' ');
          i++;
        }
      }
      r = (currentRow.methodDataBase ? currentRow.methodDataBase : '') + '  ' + str;
    } else {
      r = currentRow.methodDataBase ? currentRow.methodDataBase : '';
    }
    return r;
  }
});

async function paramCompareAdd(): Promise<void> {
  const record = {
    targetValue: '',
    sourceValue: ''
  };
  paramComoareList.push(record);
}

async function paramCompareSave() {
  moduleDialog1.value = false;
  const data = tableList.filter((p) => p.id == curId.value);
  data[0].paramCompare = JSON.stringify(paramComoareList);
}
let curId = ref('');
function handleUpdate(row) {
  curId.value = row.id;
  paramComoareList.length = 0;
  console.log(row.paramCompare);
  Object.assign(paramComoareList, row.paramCompare ? JSON.parse(row.paramCompare) : []);
  moduleDialog1.value = true;
}

function handleParamCompareDelte(index) {
  paramComoareList.splice(index, 1);
}

/**页面初始化 */
function initPage(row: any) {
  tableList.length = 0;
  updateTableList.length = 0;
  keyvalue.value = '';
  Object.assign(currentRow, row);
  if (currentRow.dataType == 'WEB') {
    currentRow.dataTypeName = '导入XML模板';
  } else if (currentRow.dataType == 'JSON') {
    currentRow.dataTypeName = '导入JSON模板';
  } else if (currentRow.dataType == 'HL7') {
    currentRow.dataTypeName = '导入HL7模板';
  } else if (currentRow.dataType == 'MQ') {
    currentRow.dataTypeName = '导入MQ模板';
  }

  getDictItemsList();
  findSysInterfaceMethodExtParams();
}
//批量获取字典
async function getDictItemsList() {
  coloumTypeList.length = 0;
  let dictTreeTypeCodes: any = ['interfaceColoumType'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const severityType = dictTreeTypeItems.data.find((item) => item.code === 'interfaceColoumType');
  coloumTypeList.push(...severityType.detailDataList);
}
/**获取入参参数对照 */
function findSysInterfaceMethodExtParams() {
  tableList.length = 0;
  const url = '/api/sys/sys-interface-meth-ext-param/findSysInterfaceMethExtParamList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { interfaceMethodId: currentRow.id, keyValue: keyvalue.value }
    })
    .then((res: any) => {
      if (res && res.data && res.data.length > 0) {
        let queryList = res.data.filter((x) => x.type == 1);
        let updateList = res.data.filter((x) => x.type == 2);
        Object.assign(tableList, queryList);
        Object.assign(updateTableList, updateList);
        Object.assign(currentParamRow, res.data[0]);
      } else {
        if (currentParamRow && !IsEmpty(currentParamRow.id)) {
          currentParamRow.id = null;
        }
      }
    })
    .catch((err: any) => {
      VxeMessage('获取表格数据异常', VxeNotifyType.error);
    });
}
/**新增条件 */
function insertRow() {
  tableList.push(Object.assign({}, baseRow));
}

/**入参字段选中事件 */
function pulldownSelectConfirm(e) {
  if (e.isChild) {
    e.aimKeys.forEach((m) => {
      console.log(e.childIndex);
      const data = tableList.filter((p) => p.id == e.childIndex);
      console.log(data);
      tableList.filter((p) => p.id == e.childIndex)[0][m.aimKey] = e.row[m.rowKey];
      console.log(tableList);
      // tableList[e.childIndex][m.aimKey] = e.row[m.rowKey];
    });
  }
}
/**入参字段选中事件 */
function pulldownSelectConfirmByUpdate(e) {
  if (e.isChild) {
    e.aimKeys.forEach((m) => {
      updateTableList.filter((p) => p.id == e.childIndex)[0][m.aimKey] = e.row[m.rowKey];
      // updateTableList[e.childIndex][m.aimKey] = e.row[m.rowKey];
    });
  }
}
/**数据类型显示文本 */
function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}
/**参数行选中改变 */
function extCurrentRowChange({ row }) {
  Object.assign(currentParamRow, row);
}

/**参数修改行选中改变 */
function extCurrentRowChangeByUpdate({ row }) {
  Object.assign(currentParamRowByUpdate, row);
}
/**保存配置 */
function saveInfo() {
  const url = '/api/sys/sysInterfaceMethod/saveOrUpdateInterfaceMethod';
  const obj: any = {};
  currentRow.methodData = sqlStrFullTxt.value;
  currentRow.repParam = null;
  currentRow.reqParam = null;
  obj.methodList = [currentRow];
  proxy.$http
    .post(url, obj)
    .then((res: any) => {
      //VxeMessage('更新成功', VxeNotifyType.success);
      saveSysInterfaceExtParams();
    })
    .catch((err: any) => {
      VxeMessage('更新失败', VxeNotifyType.success);
    });
}
/**保存参数 */
async function saveSysInterfaceExtParams() {
  let updateRecords = tableList;
  let updateTables = updateTableList;
  updateRecords.forEach((e) => {
    e.interfaceId = currentRow.interfaceId;
    e.interfaceMethodId = currentRow.id;
    e.interfaceMethodDictId = e.inCodeId;
  });
  updateTables.forEach((e) => {
    e.interfaceId = currentRow.interfaceId;
    e.interfaceMethodId = currentRow.id;
    e.interfaceMethodDictId = e.inCodeId;
  });
  let records = updateRecords.concat(updateTables);
  if (records && records.length > 0) {
    const url = '/api/sys/sys-interface-meth-ext-param/batchSaveSysInterfaceMethExtParam';
    proxy.$http
      .post(url, records)
      .then((res: any) => {
        VxeMessage('更新成功', VxeNotifyType.success);
        proxy.$emit('sucCallBack');
      })
      .catch((err: any) => {
        VxeMessage('更新失败', VxeNotifyType.error);
      });
  } else {
    proxy.$emit('sucCallBack');
  }
}
/**删除参数 */
async function deleteExtParam() {
  const $xTable = proxy.$refs.extParamsTableRef as any;
  const selectRows = $xTable.getCheckboxRecords();
  if (!selectRows || selectRows.length == 0) {
    VxeMessage('请选中要删除的行', VxeNotifyType.warning);
    return;
  }
  const type = await VXETable.modal.confirm('确定删除选中记录?'); /*不能改el  $confirm 回车事件冒泡你*/
  if (type === 'confirm') {
    const url = `/api/sys/sys-interface-meth-ext-param/batchDeleteSysInterfaceMethExtParam`;
    proxy.$http
      .post(url, selectRows)
      .then(async (res: any) => {
        findSysInterfaceMethodExtParams();
      })
      .catch((err: any) => {
        VxeMessage('取消检验失败', VxeNotifyType.error);
      });
  }
}

async function upload() {
  const { file } = await VXETable.readFile();
  uploadByUrl(file);
}
function uploadByUrl(file) {
  let url = '/api/sys/sysInterfaceMethod/uploadJsonInterfaceMethodParam';
  const fd = new FormData();
  fd.append('file', file);
  fd.append('interfaceId', currentRow.interfaceId);
  fd.append('interfaceMethodId', currentRow.id);
  fd.append('interfaceDictId', currentRow.interfaceDictId);
  fd.append('dataType', currentRow.dataType);
  proxy.$http
    .post(url, fd)
    .then((res: any) => {
      findSysInterfaceMethodExtParams();
    })
    .catch((err) => {
      (this as any).$XModal.message({ content: err.data.error.message, status: 'warning' });
    });
}

function copy() {
  const $xTable = proxy.$refs.extParamsTableRef as any;
  const selectRows = $xTable.getCheckboxRecords();
  if (selectRows.length == 0) {
    VxeMessage('请选择要复制的数据', VxeNotifyType.error);
    return;
  }
  VxeMessage('已复制到剪贴板', VxeNotifyType.success);
  sessionStorage.setItem('hl7inparamcopy', JSON.stringify(selectRows));
}

/**粘贴 */
function paste() {
  const a = sessionStorage.getItem('hl7inparamcopy');
  const b = JSON.parse(a);
  if (IsEmpty(b) || IsEmpty(a)) {
    VxeMessage('没有要粘贴的数据', VxeNotifyType.warning);
    return;
  }
  b.forEach((e) => {
    e.id = null;
    e.interfaceId = currentRow.interfaceId;
    e.interfaceMethodId = currentRow.id;
    e.interfaceMethodDictId = e.inCodeId;
  });
  const url = '/api/sys/sys-interface-meth-ext-param/batchSaveSysInterfaceMethExtParam';
  proxy.$http
    .post(url, b)
    .then((res: any) => {
      VxeMessage('粘贴成功', VxeNotifyType.success);
      proxy.$emit('sucCallBack');
    })
    .catch((err: any) => {
      VxeMessage('粘贴失败', VxeNotifyType.error);
    });
}

function synchronousParam() {
  tableList.length = 0;
  const url = '/api/sys/sys-interface-meth-ext-param/synchronousParam';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { interfaceDictId: currentRow.interfaceDictId, interfaceMethodId: currentRow.id, interfaceId: currentRow.interfaceId }
    })
    .then((res: any) => {
      findSysInterfaceMethodExtParams();
    })
    .catch((err: any) => {
      VxeMessage('获取表格数据异常', VxeNotifyType.error);
    });
}

// 新建一级机构/子结构
async function addParam(parentids: any, row: any): Promise<void> {
  const $table = proxy.$refs.extParamsTableRef as any;
  if ($table) {
    // 获取新增的数据记录
    const record: any = {
      id: null,
      extCode: '',
      extCodeNa: '',
      extCodeDtype: '',
      extCodeDes: '',
      extIsNull: 0,
      symbol: 'equal',
      inCodeId: '',
      inCodeNo: '',
      inCodeNa: '',
      isFixed: '',
      inCodeDtype: '',
      inCodeDes: '',
      paramCompare: '',
      isEnable: '',
      seq: '',
      interfaceMethodId: '',
      interfaceId: '',
      interfaceMethodDictId: '',
      leftBracket: 0,
      rightBracket: 0,
      relation: 'and',
      type: 1,
      parentId: parentids != '' || parentids != null ? parentids : null
    };
    const { row: newRow } = await $table.insertAt(record, -1);
    await $table.setEditRow(record);
    if (row) {
      await $table.setTreeExpand(row, true); // 新建一行空数据时展开这一栏
    }
  }
}
</script>

<style lang="scss" scoped>
#interMethodExternalDiv {
  height: 100%;

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  //右侧质控项目表格
  .tableBox {
    height: calc(100% - 40px);
    background-color: $base-white;
  }
}
</style>
